package com.example.demo.controller;

import com.example.demo.constant.Constant;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.SecurityUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.catalina.User;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.ServletContextPropertyUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //登录接口
    @RequestMapping("/login")
    public Result login(String userName,String password){


        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码不能为空");
        }

        UserInfo userInfo = userService.queryUserByName(userName);
        if(userInfo== null || userInfo.getId()<=0){
            return Result.fail("用户不存在");
        }
        //密码校验
//        if (!password.equals(userInfo.getPassword())){
//            return Result.fail("密码错误");
//        }
        if (!SecurityUtils.verify(password,userInfo.getPassword())){
            return Result.fail("密码错误");
        }



        //密码正确了,生成token
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constant.USER_CLAIM_ID, userInfo.getId());
        claim.put(Constant.USER_CLAIM_NAME, userInfo.getUserName());
        return Result.success(JwtUtils.genToken(claim));
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){

        String user_token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserIdToken(user_token);
        if(userId == null || userId <= 0){
            return null;
        }

        UserInfo userInfo = userService.queryUserById(userId);
        userInfo.setPassword("");
        return userInfo;

    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){

        if (blogId != null && blogId < 1 ){
            return null;
        }
        UserInfo authorInfoByBlogId = userService.getAuthorInfoByBlogId(blogId);
        authorInfoByBlogId.setPassword("");
        return authorInfoByBlogId;

    }

}
